package com.swpu.cbg.cnshop.http;

import android.content.Context;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.squareup.okhttp.Response;
import com.swpu.cbg.cnshop.bean.PageContent;


import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by chenboge on 16/2/15.
 */
public class Pager {

    private static Builder builder;
    private OkHttpHelper mHelper;
    private static final int STATE_NORMAL = 0;
    private static final int STATE_REFRESH = 1;
    private static final int STATE_LOADMORE = 2;
    private int state = STATE_NORMAL;

    private Pager() {
        mHelper = OkHttpHelper.getInstance();
        initRefreshLayout();
    }

    public void request() {
        requestData();
    }

    public static Builder newBuilder() {
        builder = new Builder();
        return  builder;
    }

    private void initRefreshLayout() {
        builder.mMaterialRefreshLayout.setLoadMore(builder.loadMore);
        builder.mMaterialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                reFreshData();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                loadMOreData();
            }

            @Override
            public void onfinish() {
                super.onfinish();
            }
        });
    }

    public void putParamter(String key,Object value) {
        builder.params.put(key, value);
    }

    private void reFreshData() {
        builder.curPage = 1;
        state = STATE_REFRESH;
        requestData();
    }

    private void loadMOreData() {
        if (builder.curPage <= builder.totlePage) {
            builder.curPage = ++builder.curPage;
            state = STATE_LOADMORE;
            requestData();
        } else {
            Toast.makeText(builder.mContext, "数据已加载到最后一页", Toast.LENGTH_SHORT).show();
            builder.mMaterialRefreshLayout.finishRefreshLoadMore();
        }
    }


    public void requestData() {
        mHelper = OkHttpHelper.getInstance();
        String s=builder.url+builder.getParams();
        mHelper.get(builder.url+builder.getParams(),null, new httpCallBack(builder.mContext));

    }

    private <T> void initRecycleViewData(List<T> data, int totlePage, int totleCount) {
        switch (state) {
            case STATE_NORMAL:
                builder.onPagerListener.load(data, totlePage, totleCount);
                break;
            case STATE_LOADMORE:
                builder.onPagerListener.loadMore(data, totlePage, totleCount);
                builder.mMaterialRefreshLayout.finishRefreshLoadMore();
                break;
            case STATE_REFRESH:
                builder.onPagerListener.refresh(data, totlePage, totleCount);
                builder.mMaterialRefreshLayout.finishRefresh();
                break;
        }

    }


    public static class Builder {

        private String url;
        private boolean loadMore;
        private int curPage = 1;
        private int pageSize = 10;
        private int totlePage = 1;
        private Context mContext;
        private Type mType;
        private MaterialRefreshLayout mMaterialRefreshLayout;
        private OnPagerListener onPagerListener;
        private HashMap<String, Object> params = new HashMap<>(5);

        public Builder setUrl(String url) {
            this.url = url;
            return builder;
        }


        public Builder setOnPagerListener(OnPagerListener onPagerListener) {
            this.onPagerListener = onPagerListener;
            return builder;
        }

        public Builder setLoadMore(boolean loadMore) {
            this.loadMore = loadMore;
            return builder;
        }

        public Builder setCurPage(int curPage) {
            this.curPage = curPage;
            return builder;
        }

        public Builder putParamter(String key,Object value) {
            params.put(key, value);
            return builder;
        }

        public Builder setPageSize(int pageSize) {
            this.pageSize = pageSize;
            return builder;
        }

        public Builder setmMaterialRefreshLayout(MaterialRefreshLayout mMaterialRefreshLayout) {
            this.mMaterialRefreshLayout = mMaterialRefreshLayout;
            return builder;
        }

        private String buildUrl() {
            return getParams();
        }

        private String getParams() {
            StringBuilder stringBuilder = null;
            params.put("curPage", curPage);
            params.put("pageSize", pageSize);
            stringBuilder = new StringBuilder("?");
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            String mUrl = stringBuilder.toString();
            if (mUrl.endsWith("&")) {
                mUrl = mUrl.substring(0, mUrl.length() - 1);
            }

            return mUrl;
        }

        public Pager builder(Context context,Type type) {
            this.mContext = context;
            this.mType = type;
            judge();
            return new Pager();

        }

        private void judge(){
            if(mContext==null) {
                throw new RuntimeException("context can not be null");
            }

            if(url==null) {
                throw new RuntimeException("url can not be null");
            }

            if(mMaterialRefreshLayout==null) {
                throw new RuntimeException("mMaterialRefreshLayout can not be null");
            }

            if(onPagerListener==null) {
                throw new RuntimeException("onPagerListener can not be null");
            }
        }

    }


    private class httpCallBack<T> extends SpotsCallback<PageContent<T>> {

        public httpCallBack(Context mContext) {
            super(mContext);
            super.mType = builder.mType;
        }
        @Override
        public void onSuccess(Response response, PageContent<T> tPageContent) {
           // mWares = warePageContent.getList();
            builder.totlePage = tPageContent.getTotalPage();
            builder.curPage = tPageContent.getCurrentPage();
            initRecycleViewData(tPageContent.getList(),builder.totlePage,tPageContent.getTotalCount());
        }


        @Override
        public void onError(Response response, int code, Exception e) {

        }

        @Override
        public void onTokenError(Response response, int code) {

        }
    }

    public interface OnPagerListener<T> {
        public void load(List<T> data, int totlePage, int totleCount);

        public void loadMore(List<T> data, int totlePage, int totleCount);

        public void refresh(List<T> data, int totlePage, int totleCount);
    }
}
